package monitor

import (
	"github.com/gin-gonic/gin"
	"ruoyi-go/app/admin/model/constants"
	"ruoyi-go/app/admin/model/monitor"
	"ruoyi-go/pkg/cache/redisCache"
	"ruoyi-go/utils/R"
	"strings"
)

func CacheHandler(context *gin.Context) {
	var list []monitor.SysCache
	list = append(list, monitor.SysCache{
		CacheName: constants.LoginCacheKey,
		Remark:    "用户信息",
	})
	list = append(list, monitor.SysCache{
		CacheName: "sys_config:",
		Remark:    "配置信息",
	})
	list = append(list, monitor.SysCache{
		CacheName: constants.SysDictCacheKey,
		Remark:    "数据字典",
	})
	list = append(list, monitor.SysCache{
		CacheName: "captcha_codes:",
		Remark:    "验证码",
	})
	list = append(list, monitor.SysCache{
		CacheName: "repeat_submit:",
		Remark:    "防重提交",
	})
	list = append(list, monitor.SysCache{
		CacheName: "rate_limit:",
		Remark:    "限流处理",
	})
	list = append(list, monitor.SysCache{
		CacheName: "pwd_err_cnt:",
		Remark:    "密码错误次数",
	})

	//config := redisCache.RedisDB.GetConfig()
	info := redisCache.RedisDB.GetInfo()
	if info["db0"] != "" {
		val := info["db0"]
		split := strings.Split(val, ",")
		for _, v := range split {
			if strings.Contains(v, "keys=") {
				info["keySize"] = strings.Trim(v, "keys=")
			}
		}
	}

	// 返回结果封装
	res := make(map[string]any)
	res["list"] = list
	res["info"] = info
	R.SuccessData(context, res)
}

func GetCacheKeysHandler(context *gin.Context) {
	cacheName := context.Param("cacheName")
	keys, _, err := redisCache.RedisDB.Scan(0, cacheName+"*", constants.ScanCountMax)
	if err != nil {
		panic(err.Error())
	}
	R.SuccessData(context, keys)
}

func GetCacheValueHandler(context *gin.Context) {
	cacheName := context.Param("cacheName")
	cacheKey := context.Param("cacheKey")
	value, err := redisCache.RedisDB.Get(cacheKey)
	if err != nil {
		panic(err.Error())
	}
	var cache = monitor.SysCache{
		CacheName:  cacheName,
		CacheKey:   cacheKey,
		CacheValue: value,
	}
	R.SuccessData(context, cache)
}

func ClearCacheNameHandler(context *gin.Context) {
	cacheName := context.Param("cacheName")
	keys, _, err := redisCache.RedisDB.Scan(0, cacheName+"*", constants.ScanCountMax)
	if err != nil {
		panic(err.Error())
	}
	for i := range keys {
		redisCache.RedisDB.Del(keys[i])
	}
	R.Success(context)
}

func ClearCacheKeyHandler(context *gin.Context) {
	cacheKey := context.Param("cacheKey")
	_, err := redisCache.RedisDB.Del(cacheKey)
	if err != nil {
		panic(err.Error())
		return
	}
	R.Success(context)
}

func ClearCacheAllHandler(context *gin.Context) {
	keys, _, err := redisCache.RedisDB.Scan(0, "*", constants.ScanCountMax)
	if err != nil {
		panic(err.Error())
	}
	for i := range keys {
		redisCache.RedisDB.Del(keys[i])
	}
	R.Success(context)
}
